package android.FiltrosJava;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;

public class DrawSprite extends AbstractImageBasic{
	protected BufferedImage sprite = null;
	protected int numCoord = 5;
	protected AbstractImageBasic spriteTrans = null;
	public DrawSprite(BufferedImage img, int numSprites){
		setSprite(img, numSprites);
	}
	
	public void setSprite(BufferedImage img, int numSprites){
		sprite = img;
		numCoord = numSprites;
	}
	
	public void setSpriteTransformation(AbstractImageBasic spriteTransformation){
		spriteTrans = spriteTransformation;
	}
	
	public BufferedImage applyFilter(BufferedImage src) {
		
		if (Math.min(src.getHeight(),src.getWidth()) < 350){
			double t = (float) ((float) Math.min(src.getHeight(),src.getWidth()) / ((float)Math.min(sprite.getHeight(),sprite.getWidth())));			
			double tam = (float) (1 - 1/t);			
			ScaleTransform st = new ScaleTransform(tam,tam);
			
			sprite = st.applyFilter(sprite);
		}				
		
		ColorModel dstCM = src.getColorModel();
		BufferedImage p = new BufferedImage(dstCM, dstCM.createCompatibleWritableRaster(src.getWidth(), src.getHeight()), dstCM.isAlphaPremultiplied(), null);        
		//BufferedImage p = new BufferedImage( src.getWidth(null), src.getHeight(null), BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = p.createGraphics();
		g.drawImage( src, 0, 0, null );		
    	g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
    	
    	if (spriteTrans != null)
    		sprite = spriteTrans.applyFilter(sprite);
    	    		
    	int[][] coord = computeCoord(sprite.getWidth(),sprite.getHeight(),src.getWidth(),src.getHeight());
    	for (int y = 0; y < numCoord; y++){    		
    		g.drawImage(sprite, coord[y][0], coord[y][1], null);    		
    	}
    	    	
		g.dispose();
		
		return p;
    }
	
	protected int[][] computeCoord(int sX, int sY, int imX, int imY){
		int[][] coord = new int[numCoord][2];
		int cont, x;
		
		for(int y = 0; y < numCoord; y++){
			cont = 0;
			coord[y][0] = (int) ((imX - sX) * Math.random());
			coord[y][1] = (int) ((imY - sY) * Math.random());
			
			x = 0;			
			while (x < y){
				cont++;
				if ((Math.abs(coord[y][0] - coord[x][0]) < sX) && (Math.abs(coord[y][1] - coord[x][1]) < sY)){
					coord[y][0] = (int) ((imX - sX) * Math.random());
					coord[y][1] = (int) ((imY - sY) * Math.random());
					x = 0;
				}else
					x++;
				
				if (cont > 30)
					x = y;
			}
		}
		
		return coord;
	}
}
